package com.ciwong.epaper.modules.evaluate.ui;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.TimeoutError;
import com.bumptech.glide.Glide;
import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.bean.HideDownloadDialogBean;
import com.ciwong.epaper.event.EventBusFactory;
import com.ciwong.epaper.modules.epaper.bean.CatalogueInfo;
import com.ciwong.epaper.modules.epaper.bean.Module;
import com.ciwong.epaper.modules.epaper.bean.ModuleContent;
import com.ciwong.epaper.modules.epaper.bean.ModuleInfo;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.modules.epaper.util.EpaperJumpManager;
import com.ciwong.epaper.modules.evaluate.util.SpeechUtils;
import com.ciwong.epaper.modules.msg.bean.Symbols;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.DialogUtil;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.FileUtil;
import com.ciwong.epaper.util.IVUtils;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.IntentValue;
import com.ciwong.epaper.util.KHBVideo.KHBVideoPlayer;
import com.ciwong.epaper.util.KHBVideo.KHBVideoPlayerStandard;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.epaper.util.download.DownLoad;
import com.ciwong.epaper.util.download.DownLoadDB;
import com.ciwong.epaper.util.download.DownLoadInfo;
import com.ciwong.epaper.util.download.DownloadStatus;
import com.ciwong.eventbus.EventBus;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.libs.utils.StringUtils;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.ThreadTask;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.ciwong.mobilelib.utils.XXPermissionTool;
import com.ciwong.mobilelib.widget.CWDialog;
import com.ciwong.mobilelib.widget.DownloadProgressBar;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloadServiceProxy;
import com.liulishuo.filedownloader.FileDownloader;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*音标视频页面*/
public class SymbolVideoActivity extends BaseActivity implements View.OnClickListener {

    private String title;

    private List<CatalogueInfo> mCatalogueInfos = new ArrayList<>();

    private List<DownLoadInfo> mDownLoadInfos = new ArrayList<>();

    private String mBookId;

    private Boolean isformNewDesk = false;

    private ArrayList<Module> mModuleList = new ArrayList<>();

    /**
     * 服务id
     */
    private int workType = 0;


    private KHBVideoPlayerStandard mKHBVideoPlayerStandard;
    private TextView textView;

    private ImageView symbolContentImg;

    private ImageView symbolVideoPlay;

    private LinearLayout symbolDoworkBtn;

    private long effectiveDate = -1;


    private int packageId;

    private String cId;

    private int moduleId;

    private String versionId;

    private String description;

    private String picture;


    private DownLoadInfo downLoadInfo;


    private Symbols symbols;

    private String symbol;

    /**
     * 视频本地保存地址
     */
    private String localVideoPath, localAudioPath;

    /**
     * 视频地址
     */
    private String videoUri;


    private ModuleContent moduleContent;

    private Module mModule;


    /**
     * 加载视频视图
     */
    private void initVideoView() {
        IVUtils.setImageWidth200(mKHBVideoPlayerStandard.thumbImageView, null);
        initDataView();
//        showGetPermissDialog();
    }

    private final int CODE_REQUEST_WRITESD_PERMISSION = 8800;
    private CWDialog getSDcardPermissDialog;

    /**
     * 获取SDcard权限提示框
     */
    private boolean showGetPermissDialog() {
        boolean isHavePermiss = XXPermissionTool.isHasPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (isHavePermiss) {
            checkSDcardpermiss();
        } else {
            if (getSDcardPermissDialog == null) {
                getSDcardPermissDialog = new CWDialog(this);
                getSDcardPermissDialog.setTitle(R.string.get_permiss_title);
                getSDcardPermissDialog.setTitleTextColor(Color.BLACK);
                getSDcardPermissDialog.setMessage(getString(R.string.get_sdcard_permiss_content), 16, Color.BLACK, Gravity.LEFT);
                getSDcardPermissDialog.setPositiveButton(R.string.get_permiss_ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getSDcardPermissDialog.dismiss();
                        checkSDcardpermiss();
                    }
                });
                getSDcardPermissDialog.setNegativeButton(R.string.get_permiss_no, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getSDcardPermissDialog.dismiss();
                    }
                });
            }
            getSDcardPermissDialog.show();
        }
        return true;
    }

    /**
     * 使用sd卡，判断权限
     */
    private boolean checkSDcardpermiss() {
        if (Build.VERSION.SDK_INT >= 23
                && getApplicationInfo().targetSdkVersion >= 23) {
            List<String> permissionList = new ArrayList<String>();
            Map<String, String> noteMap = new HashMap<>();
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            noteMap.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, "读写本地存储权限");
            XXPermissionTool.checkPermissions(this, //
                    permissionList, //
                    noteMap, //
                    CODE_REQUEST_WRITESD_PERMISSION, //
                    new XXPermissionTool.OnCheckPermissionsFinishedListener() {
                        @Override
                        public void onCheckPermissionsFinished(int flag) {
                            if (0 == flag) {
                                initDataView();
                            }
                        }
                    });
        } else {
            initDataView();
        }
        return true;
    }

    private void initView() {
        setTitleText(title + "-" + "[" + symbol + "]");
    }

    private void dismissProgress() {
        hideMiddleProgressBar();
    }


    @Override
    protected int setView() {
        return R.layout.activity_phonetic_symbol_video_play;
    }

    @Override
    protected void findViews() {
        mKHBVideoPlayerStandard = (KHBVideoPlayerStandard) findViewById(R.id.symbol_content_video);
        textView = (TextView) findViewById(R.id.symbol_text);
        symbolContentImg = (ImageView) findViewById(R.id.symbol_content_img);
        symbolVideoPlay = (ImageView) findViewById(R.id.symbol_video_play);
        symbolDoworkBtn = (LinearLayout) findViewById(R.id.rl_dub_result_submit);
    }

    @Override
    protected void initEvent() {
        symbolVideoPlay.setOnClickListener(this);
        symbolDoworkBtn.setOnClickListener(this);

        setDownloadProgressOnDismissListener(new DownloadProgressBar.OnDownLoadDialogDismissListener() {
            @Override
            public void ondDismiss(DownloadProgressBar downloadProgressBar) {
                if (downLoadInfo != null) {
                    int status = downLoadInfo.getStatus();
                    if (status == DownloadStatus.STATUS_LOADING || status == DownloadStatus.STATUS_DOWNLOADING) {
                        DownLoad.getInstance().pauseTask(downLoadInfo);
                    }
                }
            }
        });
        EventBus.getDefault().register(this);
    }

    @Override
    protected void init() {
        mKHBVideoPlayerStandard.setNormalView(true);
        initdata();
    }

    protected void initdata() {
        Intent intent = getIntent();
        symbols = (Symbols) intent.getSerializableExtra(IntentFlag.INTENT_FLAG_SYMBOL);
        effectiveDate = intent.getLongExtra(IntentFlag.INTENT_FLAG_WORK_EFFECTIV_TIME, 0);
        description = symbols.getDescription();
        symbol = this.symbols.getSymbols();
        title = this.symbols.getLevel3();
        picture = this.symbols.getPicture();
        moduleId = this.symbols.getModuleId();
        packageId = this.symbols.getPackageId();
        mBookId = packageId + "";
        cId = this.symbols.getcId();
        versionId = this.symbols.getVersionId();
        videoUri = this.symbols.getVideo();
        textView.setText(description);
        textView.setTextSize(20);
        Glide.with(this).load(Uri.parse(picture)).into(symbolContentImg);
        /*Bitmap bitMap = getBitMap(picture);
        symbolContentImg.setImageBitmap(bitMap);*/
        initVideoView();
        initView();
    }


    @Override
    protected void loadData() {
        showCricleProgress();
        getLocData();
    }

    @Override
    protected void onResume() {

        if (!EventBus.getDownLoadInstance().isRegistered(this)) {
            EventBus.getDownLoadInstance().register(this);
        }
        super.onResume();
    }

    @Override
    protected void onStop() {
        if (EventBus.getDownLoadInstance().isRegistered(this) && !isTopActivity()) {
            EventBus.getDownLoadInstance().unregister(this);
            hideDownloadProgress();
        }
        super.onStop();
    }

    @Override
    protected void onPause() {
        super.onPause();
        KHBVideoPlayer.releaseAllVideos();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDownLoadInstance().isRegistered(this)) {
            EventBus.getDownLoadInstance().unregister(this);
        }
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.symbol_video_play) {//播放
            mKHBVideoPlayerStandard.startVideo(KHBVideoPlayer.PLAY_MODE_UNMUTE);
        } else if (id == R.id.rl_dub_result_submit) {
            downLoadInfo = getDownLoadInfo(moduleContent, mModule);
            doClickListener(moduleContent, downLoadInfo, true);
//            showGetPermissDialog2(moduleContent, downLoadInfo, true);
        }
    }


    /**
     * 来自新的首页同步教材  查询数据库方法
     *
     * @param moduleContent
     * @param module
     * @return
     */
    private DownLoadInfo getDownLoadInfo(ModuleContent moduleContent, Module module) {
        DownLoadInfo downLoadInfo = null;
        try {

            downLoadInfo = DownLoadDB.queryDownloadInfoByBookIdAndChapterIdAndMoudleidAndVerid(mBookId,
                    module.getModuleInfo().getcId(),
                    module.getModuleInfo().getModuleId() + "",
                    moduleContent.getVersionId());
        } catch (Exception e) {
            e.getStackTrace();
        }
        try {
            if (null == downLoadInfo) {
                downLoadInfo = new DownLoadInfo();
                String url = moduleContent.getResourceUrl();
                downLoadInfo.setUrl(url);
                downLoadInfo.setChapterId(module.getModuleInfo().getcId());
                downLoadInfo.setChapterName(moduleContent.getResourceName());
                downLoadInfo.setHash(moduleContent.getResourceType());
                downLoadInfo.setIsFree(1);
                downLoadInfo.setBookId(mBookId);
                downLoadInfo.setSavePath(FileUtil.getSavePathByUrl(SymbolVideoActivity.this, url));
                //新旧包结构区分
                downLoadInfo.setType(CatalogueInfo.PackageMode.PACKAGE_MODE_NEW);
                downLoadInfo.setResourceName(title + "-" + "[" + symbol + "]");
                downLoadInfo.setResourceType(moduleContent.getResourceType());
                if (null != module) {
                    downLoadInfo.setModuleId(String.valueOf(module.getModuleInfo().getModuleId()));

                }
                downLoadInfo.setModuleName(module.getModuleInfo().getModuleName());
                downLoadInfo.setVersionId(moduleContent.getVersionId());
                String fileSize = moduleContent.getFileSize();
                if (!TextUtils.isEmpty(fileSize) && fileSize.contains(" ")) {
                    downLoadInfo.setSize(fileSize.split(" ")[0]);
                }
            }
        } catch (Exception e) {
            e.getStackTrace();
        }

        return downLoadInfo;
    }

    private CWDialog getSDcardPermissDialog2;

    /**
     * 获取SDcard权限提示框
     */
    private boolean showGetPermissDialog2(final ModuleContent moduleContent, final DownLoadInfo downLoadInfo, final boolean isHandClick) {
        boolean isHavePermiss = XXPermissionTool.isHasPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (Build.VERSION.SDK_INT < 23 || isHavePermiss) {
            checkSDcardpermiss(moduleContent, downLoadInfo, true);
        } else {
            if (getSDcardPermissDialog2 == null) {
                getSDcardPermissDialog2 = new CWDialog(this);
                getSDcardPermissDialog2.setTitle(R.string.get_permiss_title);
                getSDcardPermissDialog2.setTitleTextColor(Color.BLACK);
                getSDcardPermissDialog2.setMessage(getString(R.string.get_sdcard_permiss_content), 16, Color.BLACK, Gravity.LEFT);
                getSDcardPermissDialog2.setPositiveButton(R.string.get_permiss_ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getSDcardPermissDialog2.dismiss();
                        checkSDcardpermiss(moduleContent, downLoadInfo, true);
                    }
                });
                getSDcardPermissDialog2.setNegativeButton(R.string.get_permiss_no, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getSDcardPermissDialog2.dismiss();
                    }
                });
            }
            getSDcardPermissDialog2.show();
        }
        return true;
    }

    /**
     * 使用sd卡，判断权限
     */
    private boolean checkSDcardpermiss(final ModuleContent moduleContent, final DownLoadInfo downLoadInfo, final boolean isHandClick) {
        if (Build.VERSION.SDK_INT >= 23
                && getApplicationInfo().targetSdkVersion >= 23) {
            List<String> permissionList = new ArrayList<String>();
            Map<String, String> noteMap = new HashMap<>();
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            noteMap.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, "读写本地存储权限");
            XXPermissionTool.checkPermissions(this, //
                    permissionList, //
                    noteMap, //
                    CODE_REQUEST_WRITESD_PERMISSION, //
                    new XXPermissionTool.OnCheckPermissionsFinishedListener() {
                        @Override
                        public void onCheckPermissionsFinished(int flag) {
                            if (0 == flag) {
                                doClickListener(moduleContent, downLoadInfo, true);
                            }
                        }
                    });
        } else {
            doClickListener(moduleContent, downLoadInfo, true);
        }
        return false;
    }

    /**
     * item监听事件
     *
     * @param downLoadInfo
     */
    public void doClickListener(final ModuleContent moduleContent, final DownLoadInfo downLoadInfo, boolean isHandClick) {


        if (ModuleInfo.ModuleInfoId.MODULE_ID_ESSAY == Integer.valueOf(downLoadInfo.getModuleId())) {
            //新闻不用下载资源
            downloadComplete(moduleContent, downLoadInfo, isHandClick);
            return;
        }

        if (TextUtils.isEmpty(downLoadInfo.getUrl())) {
            showToastError(R.string.package_no_publish2);
            return;
        }


        switch (downLoadInfo.getStatus()) {
            case DownloadStatus.STATUS_NORMAL:
            case DownloadStatus.STATUS_FAILED:
            case DownloadStatus.STATUS_FAILED_SDISFULL:
            case DownloadStatus.STATUS_FAILED_UNZIP:
            case DownloadStatus.STATUS_UPZIPING:
                if (DialogUtil
                        .sdIsFullForDownload(SymbolVideoActivity.this, downLoadInfo)) {
                    DialogUtil.showSdFullDialog(
                            SymbolVideoActivity.this,
                            downLoadInfo.getSize());
                    return;
                }

                judgeDownloadMethod(moduleContent, downLoadInfo);
                break;
            case DownloadStatus.STATUS_LOADING:
                //                DownLoad.getInstance().pauseTask(downLoadInfo);
                DownLoad.getInstance().resumeTask(downLoadInfo);
                break;
            case DownloadStatus.STATUS_DOWNLOADING:
                DownLoad.getInstance().pauseTask(downLoadInfo);
                break;
            case DownloadStatus.STATUS_PAUSE:
                if (NetworkUtils.isOnline()) {
                    if (NetworkUtils.isWifiOnline()) {
                        showDownloadDialog();
                        DownLoad.getInstance().resumeTask(downLoadInfo);
                    } else {
                        DialogUtil.showWIFIDialogOfNewContent(
                                SymbolVideoActivity.this,
                                downLoadInfo, moduleContent, null, 0);
                    }
                } else {
                    ToastUtil.INSTANCE.toastCenterNoNetError();
                }
                break;
            //            case DownloadStatus.STATUS_UPZIPING:
            //                // DownLoad.getInstance().addTask(info);
            //                break;
            case DownloadStatus.STATUS_COMPLETED:
                //新包拆分逻辑增加 资源 versionId,
                //String catalogueJsonPath = ESystem.getPackagesCatalogueJsonPath(downLoadInfo.getBookId(), downLoadInfo.getChapterId());
                String resourcePath = ESystem.getPackagesJsonPathNew(downLoadInfo.getBookId(), downLoadInfo.getChapterId(), downLoadInfo.getModuleId(), moduleContent.getVersionId());
                //服务权限判断，跳转资源详情页

                if (new File(resourcePath).exists()) {
                    downloadComplete(moduleContent, downLoadInfo, isHandClick);
                    //                            EpaperJumpManager.jumpToContent(R.string.go_back, NewContentActivity2.this, downLoadInfo, mServiceId, mEpaperInfo, mEpaperServerList);
                } else {
                    downLoadInfo.setStatus(DownloadStatus.STATUS_NORMAL);
                    downLoadInfo.setProgress(0);
                    judgeDownloadMethod(moduleContent, downLoadInfo);
                }

                break;
        }
    }

    /**
     * 设置视频播放资源
     */
    private void initDataView() {
        localVideoPath = ESystem.getDubingVideoPath() + File.separator + StringUtils.md5(videoUri.toString());
        File targetFile = new File(localVideoPath);
        if (targetFile.exists()) {
            mKHBVideoPlayerStandard.setplsyModeUrlUp(localVideoPath, KHBVideoPlayer.SCREEN_LAYOUT_LIST, KHBVideoPlayer.PLAY_MODE_UNMUTE, "");
        } else {
            mKHBVideoPlayerStandard.setplsyModeUrlUp(videoUri.toString(), KHBVideoPlayer.SCREEN_LAYOUT_LIST, KHBVideoPlayer.PLAY_MODE_UNMUTE, "");
            downWork(videoUri.toString(), localVideoPath);
        }
        mKHBVideoPlayerStandard.startVideo(KHBVideoPlayer.PLAY_MODE_UNMUTE);

    }

    private BaseDownloadTask task;

    public void downWork(String videoUrl, String localVideoPath) {
        //下载视频
        try {
            FileDownloader mFileDownloader = FileDownloader.getImpl();
            mFileDownloader.setMaxNetworkThreadCount(2);
            if (null != task && task.isRunning()) {
                task.cancel();
            }
            task = mFileDownloader.create(videoUrl)
                    .setPath(localVideoPath)
                    .setAutoRetryTimes(3)
                    .setTag(videoUrl)
                    .setForceReDownload(true)
                    .setListener(fileDownloadListener);
            task.start();
        } catch (Exception e) {
            e.getStackTrace();
        }
    }

    FileDownloadListener fileDownloadListener = new FileDownloadListener() {

        @Override
        protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {

            CWLog.d("down", "down_penging");
        }


        @Override
        protected void connected(BaseDownloadTask task, String etag, boolean isContinue, int soFarBytes, int totalBytes) {

            CWLog.d("down", "down_connected");
        }

        @Override
        protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {

            CWLog.d("down", "down_connected");
        }

        @Override
        protected void completed(BaseDownloadTask task) {
        }

        @Override
        protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {

        }

        @Override
        protected void error(BaseDownloadTask task, Throwable e) {
            task.cancel();
        }

        @Override
        protected void warn(BaseDownloadTask task) {
            CWLog.d("down", "down_warn");

        }
    };

    private void getModule(ArrayList<Module> mModuleList) {
        if (mModuleList == null || mModuleList.size() == 0) {
        } else {
            //获取本音标
            for (int i = 0; i < mModuleList.size(); i++) {
                Module item = mModuleList.get(i);
                boolean isSearch = false;
                if (item.getModuleInfo().getModuleId() == ModuleInfo.ModuleInfoId.MODULE_ID_REPEAT) {
                    for (int j = 0; j < item.getResourceList().size(); j++) {
                        ModuleContent mModuleContent = item.getResourceList().get(j);
                        if (versionId.equals(mModuleContent.getVersionId())) {
                            moduleContent = mModuleContent;
                            mModule = item;
                            isSearch = true;
                            break;
                        }
                    }
                }
                if (isSearch) {
                    break;
                }
            }
        }
    }

    /**
     * 获取本地数据
     */
    private void getLocData() {
        ThreadTask.getInstance().executorDBThread(new Runnable() {
            @Override
            public void run() {
                SerializableManager.getInstance().deSerialize(SerializableManager.SerializeKey.SHARE_KEY_BOOK_CHAPTER + mBookId + cId, new BaseCallBack() {
                    @Override
                    public void failed(int errorCode, Object data) {
                        loadNetData();
                    }

                    @Override
                    public void failed(Object data) {
                        loadNetData();
                    }

                    @Override
                    public void success(Object data) {
                        try {
                            if (data != null) {
                                //获取本地DownLoadInfos
                                mModuleList = (ArrayList<Module>) data;
                                getModule(mModuleList);
                            }
                            loadNetData();
                        } catch (Exception e) {
                            e.getStackTrace();
                        }

                    }
                });
            }
        }, ThreadTask.ThreadPeriod.PERIOD_HIGHT);
    }

    private void loadNetData() {

        EpaperDao.getInstance().getCatalogueResourceList(mBookId, cId, null, isformNewDesk, IntentValue.JumpToBookCatalogType.NORMAL,

                new BaseExtCallBack(SymbolVideoActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {

                    @Override
                    public void success(final Object data) {
                        try {
                            //后台没数据临时用之前的接口
                            hideCricleProgress();
                            mModuleList = (ArrayList<Module>) data;
                            getModule(mModuleList);
                        } catch (Exception e) {
                            e.getStackTrace();
                        }

                    }

                    @Override
                    public void failed(int errorCode, Object data) {
                        hideCricleProgress();
                        //网络获取失败了再走本地获取流程
                        super.failed(errorCode, data);
                        if (mModuleList == null || mModuleList.size() == 0) {
                            if (!NetworkUtils.isOnline() || data instanceof TimeoutError) {
//                                showContainerType(ContainerType.TYPE_NO_NET_FAILED);
                                ToastUtil.INSTANCE.toastCenterError("加载失败，检查网络重新请求");
                            } else if (errorCode != 17 && errorCode != 27) {
                                ToastUtil.INSTANCE.toastCenterError("加载失败，检查网络重新请求");
                            }
                        }


                    }

                    @Override
                    public void failed(Object data) {
                        hideCricleProgress();
                        //                        getLocData();
                        super.failed(data);
                        if (mModuleList == null || mModuleList.size() == 0) {
                            ToastUtil.INSTANCE.toastCenterError("加载失败，检查网络重新请求");
                        }

                    }
                });
    }


    public void showDownloadDialog() {
        showDownloadProgress();
        showCancelButtonOfDownloadProgress();
    }

    public void onEventMainThread(EventBusFactory.DownloadEvent item) {
        DownLoadInfo info = item.getInfo();
        if (info != null) {
            dealCircleProgress(info);
        }
    }

    //隐藏加载框
    public void onEventMainThread(HideDownloadDialogBean hideDownloadDialogBean) {
        hideDownloadProgress();
    }

    private void judgeDownloadMethod(ModuleContent moduleContent, DownLoadInfo downLoadInfo) {
        if (NetworkUtils.isOnline()) {
            if (NetworkUtils.isWifiOnline()) {
                showDownloadDialog();
                DownLoad.getInstance()
                        .addTask(downLoadInfo);
            } else {
                DialogUtil.showWIFIDialogOfNewContent(
                        SymbolVideoActivity.this,
                        downLoadInfo, moduleContent, null, 0);
            }
        } else {
            ToastUtil.INSTANCE.toastCenterNoNetError();
        }

    }

    private void downloadComplete(final ModuleContent moduleContent, final DownLoadInfo downLoadInfo, boolean isHandClick) {


        //        final ModuleContent moduleContent = mResourceList.get(modulePosition);
        //要区分是从扫一扫进来还是书桌进来的
        //如果最后都未空说明没购买没试用
        //        mServiceDetail = null;

        int position = 0;
        List<ModuleContent> moduleContentList = mModule.getResourceList();
        for (int i = 0; i < moduleContentList.size(); i++) {
            //versionId parentVersionId resourceType 确定唯一性
            if (moduleContent.getVersionId().equals(moduleContentList.get(i).getVersionId()) && moduleContent.getParentVersionId().equals(moduleContentList.get(i).getParentVersionId())) {
                position = i;
                moduleContentList.get(position).setResourceName(title + "-" + "[" + symbol + "]");
                break;
            }
        }
        final int moduleId;
        if (downLoadInfo != null && downLoadInfo.getType() == 1) {
            moduleId = Integer.parseInt(downLoadInfo.getModuleId());
        } else {
            moduleId = mModule.getModuleInfo().getModuleId();
        }

        if (!isHandClick) {
            boolean downloadInfoTheSame = true;

            //下载完成自动打开判断是否下载框还存在，如果不存在，不往下走
            if (!isDownloadProessBarShowing()) {
                return;
            }

            //解决打开两个不同类型作业问题
            if (!downloadInfoTheSame) {
                if (FileDownloadServiceProxy.getImpl().isIdle()) {
                    hideDownloadProgress();
                }
                return;
            }
        }


        //下载完成手动打开，加个下载加载框
        if (isHandClick) {
            showDownloadProgress();
            hideCancelButtonOfDownloadProgress();
        }
        int speekType = SpeechUtils.WordReadMode.READ_REPEAT;
        EpaperJumpManager.jumpToWordRead(R.string.go_back, SymbolVideoActivity.this, "", downLoadInfo, mModule, null, position, speekType, -1, "0", null, 0, false, null, effectiveDate);

    }

    private void dealCircleProgress(final DownLoadInfo downLoadInfo) {
        switch (downLoadInfo.getStatus()) {
            case DownloadStatus.STATUS_FILE_DOWNLOAD:
                hideDownloadHorizontalProgressBar();
                hideCancelButtonOfDownloadProgress();
                break;
            case DownloadStatus.STATUS_COMPLETED:
                String resourcePath = ESystem.getPackagesJsonPathNew(downLoadInfo.getBookId(), downLoadInfo.getChapterId(), downLoadInfo.getModuleId(), moduleContent.getVersionId());
                if (new File(resourcePath).exists()) {
                    if (downLoadInfo != null) {
                        downloadComplete(moduleContent, downLoadInfo, false);
                    } else {
                        hideDownloadProgress();
                    }
                } else {
                    //这个状态表示没有下载成功
                    downLoadInfo.setStatus(DownloadStatus.STATUS_NORMAL);
                    downLoadInfo.setProgress(0);
                    ThreadTask.getInstance().executorDBThread(new Runnable() {
                        public void run() {
                            DownLoadDB.insertDetail(downLoadInfo);
                        }
                    }, ThreadTask.ThreadPeriod.PERIOD_HIGHT);
                    hideDownloadProgress();
                    ToastUtil.INSTANCE.toastCenterError(R.string.load_failed_and_retry);
                }
                break;
            case DownloadStatus.STATUS_FAILED:
                hideDownloadProgress();
                ToastUtil.INSTANCE.toastCenterError(R.string.load_failed_and_retry);
                break;
            case DownloadStatus.STATUS_FAILED_SDISFULL:
                hideDownloadProgress();
                ToastUtil.INSTANCE.toastCenterError(R.string.load_failed_sdfull_and_retry);
                break;
            case DownloadStatus.STATUS_FAILED_UNZIP:
                hideDownloadProgress();
                ToastUtil.INSTANCE.toastCenterError(R.string.load_failed_unzip_and_retry);
                break;
            case DownloadStatus.STATUS_DOWNLOADING:
                updateDownloadProgress(downLoadInfo.getProgress());
                break;
        }
    }

}
